<?php

/** 
 * 用户订单模型
 * @property User_mdl $users
 * @property Price_mdl $price
 * @property Order_cache_mdl $orderCache
 */
class User_order_mdl extends MY_Model {
	protected $_table = 'hs_order';
	private $userID = NULL;
	public function __construct() {
		parent::__construct ();
		$this->load->model('User_mdl','users');
		$this->load->model('Price_mdl','price');
// 		$this->load->model('Order_cache_mdl','orderCache');
	}
	
	/**
	 * 重写获取表名方法
	 * 
	 * @see MY_Model::_table()
	 */
	protected function _table() {
		if ($this->userID!==NULL) {
			return $this->_table.'_'.$this->getTableId();
		}
		return $this->_table;
	}
	/**
	 * 根据用户ID计算所属分表ID
	 * @param int $uid
	 * @return number
	 */
	private function getTableId($uid=0){
		/*
		 * 当要添加更多分表时扩容的方法:
		* $tableID = floor($this->userID/10000) * 10 +　$this->userID % 10;
		* 计算结果为:
		* 			1 <= $uid < 10000 : 0  <= $tableID <= 9
		* 		10000 <= $uid < 20000 : 10 <= $tableID <= 19
		* 以此类推.
		*/
		$uid = empty($uid) ? $this->userID : $uid ;
		return $uid % 10;
	}
	/**
	 * 设置用户ID,用于分表
	 * @param int $uid
	 */
	public function setUserID($uid){
		$this->userID = (int)$uid;
	}
	
	public function checkHasUnfinishOrder($uid){
		$this->setUserID($uid);
		$where = array(
				'userID'=>$uid,
				'isFinish'=>0,
		);
		$order = $this->getOne($where,'id');
		return empty($order) ? FALSE : TRUE;
	}
	
	public function end($orderID,$takeSec){
		$order = $this->getOneById($orderID);
		if( empty($order) ){
			//TODO
		}
		// 计算水费
		$amount = $this->price->calculateAmount($takeSec,$order['type'],$order['schoolID']);
		// 更新订单
		$update = array(
				'isFinish'=>1,
				'takeSec'=>$takeSec,
				'amount'=>$amount,
				'updateTime'=>time(),
		);
		$res = $this->updateOne('id',$orderID,$update);
		
		// 向用户扣钱
		$this->users->buy($order['userID'], $amount);
		// 添加到mongo同步队列
		$this->load->model('Order_sync_queue_mdl','syncQueue');
		$this->syncQueue->enqueue($orderID,$order['userID']);
		
		return $amount;
	}
	
	public function getUserOrders($uid){
		$this->setUserID($uid);
		
		$list = $this->db->select('*')->from($this->_table())
						->where('userID',$uid)
						->order_by('isFinish','ASC')
						->order_by('id','DESC')
						->limit(20)
						->get()
						->result_array();
		return $list;
		
	}
	
	/**
	 * 后台同步脚本插入
	 */
	public function bginsert($order){
		
		$table = 'hs_order_'.$this->getTableId($order['userID']);
		
		if($this->db->insert($table,$order)){
			return $this->db->insert_id();
		}
		
		return false;
		
	}
	
}

